<?php 

namespace app\home\controller;

// 引入公共控制器
use app\common\controller\Home;

class Coupon extends Home{

    public function _initialize() {
        // 调用父类构造函数
        parent::_initialize();

        $this->CouponModel = model('Coupon.Coupon');
        $this->ReceiveModel = model('Coupon.Receive');
    }

    public function receive(){
        if($this->request->isGet()) {
            // 获取优惠券id
            $cid = $this->request->param('cid');

            // 获取优惠券信息
            $coupon = $this->CouponModel->where('id', $cid)->find()->getData();

            // 判断优惠券是否在活动时间内
            if($coupon['status'] == 0) {
                $this->error('该优惠券已过期', 'home/index/coupon');
                exit;
            }

            // 获取用户信息
            $business = $this->Business;
            // 组装数据储存至数据库中
            $data = [
                'cid' => $cid,
                'busid' => $business['id'],
                'status' => 1,
            ];
            // 储存优惠券领取信息
            // 开启事务
            $this->ReceiveModel->startTrans();
            $receiveResult = $this->ReceiveModel->save($data);

            if($receiveResult) {
                // 修改优惠券剩余数量并存至数据库
                $coupon['total'] = $coupon['total'] - 1;
                $totalResult = $this->CouponModel->save($coupon, ['id' => $cid]);
                if($totalResult) {
                    $this->ReceiveModel->commit();
                    $this->success('领取成功', 'home/index/coupon');
                } else {
                    // 回滚事务
                    $this->ReceiveModel->rollback();
                    $this->error('领取失败：' . $this->CouponModel->getError(), 'home/index/coupon');
                }
            } else {
                $this->error('领取失败：' . $this->ReceiveModel->getError(), 'home/index/coupon');
            }
        }
    }

    public function info(){
        if($this->request->isGet()) {
            // 获取优惠券id
            $cid = $this->request->param('cid');

            // 查询优惠券信息
            $coupon = $this->CouponModel->where('id', $cid)->find();

            // 获取用户信息
            $business = $this->Business;
            // 查询优惠券是否已领取
            $result = $this->ReceiveModel
            ->where('cid', $coupon['id'])
            ->where('busid', $business['id'])
            ->find();
            // 组装领取状态字段，并只把该用户领取的优惠券组装入数组
            if($result) {
                $coupon['receive_text'] = '已领取';
            } else {
                $coupon['receive_text'] = null;
            }

            if($coupon){
                // 赋值静态变量
                $this->assign('coupon', $coupon);
            } else {
                $this->error('该优惠券不存在：' . $this->CouponModel->getError(), 'home/index/coupon');
                exit;
            }
        } 

        return $this->fetch();
    }
}

?>